<?php

$app->group('/daily', function () use ($app) {
    $app->get('/', function () use ($app) {
        $app->render('daily/index.html', array('models' => array()));
    })->name('daily-home');

    $app->get('/add', function () use ($app) {
        $app->render('daily/add.html', array());
    })->name('daily-add');
    $app->post('/add', function () use ($app) {
        $reviewDate = $app->request->post('review-date');
        $content = $app->request->post('content', '');
        $tags = $app->request->post('tags', '');
        $now = new DateTime();
        $now = $now->format('c');
        $nodeTable = $app->NodeTable;
        $user = $_SESSION['user'];
        $rowCount = $nodeTable->insert(array(
            'start_date' => $reviewDate,
            'end_date' => $reviewDate,
            'period' => 'daily',
            'content' => $content,
            'user_id' => $user->id,
            'created_at' => $now,
            'updated_at' => $now
        ));

        if ($rowCount == 1) {
            $nodeId = $nodeTable->lastInsertValue;
            $nodeTagTable = $app->NodeTagsTable;

            foreach (array_unique(array_map(function ($item) {
                return trim($item);
            }, explode(',', $tags))) as $tag) {
                if ($tag) {
                    $nodeTagTable->insert(array('node_id' => $nodeId, 'tag_name' => $tag));
                }
            }
        }
        $app->redirect($app->urlFor('daily-add'), 301);
    });

    $app->get('/edit', function () use ($app) {
        $app->render('daily/add.html', array());
    })->name('daily-edit');
    $app->post('/edit', function () use ($app) {
    });

    $app->get('/view', function () use ($app) {
        $app->render('daily/view.html', array());
    })->name('daily-view');
});